<template>
  <div class="add-question">
    <h1 class="title">数学题目</h1>
    <el-form :model="form" label-width="120px">
      <el-form-item label="学科：">
        <el-input v-model="form.subject" disabled />
      </el-form-item>
      <el-form-item label="题目：">
        <el-input v-model="form.content" placeholder="请输入题目" />
      </el-form-item>
      <el-form-item label="分值：">
        <el-input-number v-model="form.score" :min="1" :max="10" />
      </el-form-item>
      <el-form-item label="难度：">
        <el-select v-model="form.difficulty" placeholder="请选择难度">
          <el-option label="简单" :value="1" />
          <el-option label="中等" :value="2" />
          <el-option label="困难" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="上传图片：">
        <el-upload
          action="/api/upload"
          :on-success="handleImageUploadSuccess"
          :before-upload="beforeImageUpload"
          :limit="1"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="选项：">
        <div v-for="(value, key) in form.options" :key="key" class="option-item">
          <span class="option-label">{{ key }}:</span>
          <el-input v-model="form.options[key]" :placeholder="`选项${key}`" />
        </div>
      </el-form-item>
      <el-form-item label="答案：">
        <el-select v-model="form.answer" placeholder="请选择正确答案">
          <el-option 
            v-for="(value, key) in form.options" 
            :key="key"
            :label="`${key}: ${value}`" 
            :value="key" 
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const form = ref({
  type: 1, // 1表示选择题
  subject: 'math',
  content: '',
  answer: '',
  difficulty: 2, // 默认中等难度
  score: 1,
  options: {
    A: '',
    B: '',
    C: '',
    D: ''
  },
  image: null,
});

// 图片上传成功处理
const handleImageUploadSuccess = (response) => {
  form.value.image = response.data.url;
  ElMessage.success('图片上传成功');
};

// 图片上传前校验
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件');
  }
  return isImage;
};

// 提交表单
const submitForm = async () => {
  try {
    // 过滤掉空值的选项
    const filteredOptions = Object.fromEntries(
      Object.entries(form.value.options).filter(([_, value]) => value.trim())
    );
    
    const payload = {
      ...form.value,
      options: filteredOptions
    };
    
    console.log('提交数据:', payload);
    
    // const response = await axios.post('http://192.168.43.63:8080/api/questions', payload, {
      const response = await axios.post('http://192.168.43.173:8080/api/questions', payload, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer '+localStorage.getItem('token')
      }
    });
    
    ElMessage.success('题目添加成功');
    resetForm();
  } catch (error) {
    console.error('提交错误:', error.response);
    ElMessage.error(`题目添加失败: ${error.response?.data?.message || error.message}`);
  }
};

// 重置表单
const resetForm = () => {
  form.value = {
    type: 1,
    subject: 'math',
    content: '',
    answer: '',
    difficulty: 2,
    score: 1,
    options: {
      A: '',
      B: '',
      C: '',
      D: ''
    },
    image: null,
  };
};
</script>

<style scoped>
.title {
  text-align: center;
  font-size: 28px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #333;
}
.add-question {
  padding: 20px;
}
.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.option-label {
  width: 30px;
  font-weight: bold;
}
</style>